const express = require('express')
const router = express.Router()
const { CoustomerModel } = require('../model/index')

router.post('/storerecords', (req, res, next) => {
  const { username, records } = req.body
  // console.log(username, records)
  // new CoustomerModel({ username, records }).save()
  //   .then(resp => {
  //     res.json({
  //       code: 200,
  //       data: resp
  //     })
  //   }).catch(err => {
  //     res.json({
  //       code: 500,
  //       data: err
  //     })
  //   })
  CoustomerModel.find({ username }, (err, data1) => {
    if (err) {
      res.json({
        code: 500,
        data: err
      })
    } else {
      if (data1.length === 0) {
        // console.log(username, records)
        new CoustomerModel({ username, records }).save()
          .then(resp => {
            res.json({
              code: 200,
              data: resp
            })
          }).catch(err => {
            res.json({
              code: 500,
              data: err
            })
          })
      } else {
        CoustomerModel.deleteOne({ username }, (err, data2) => {
          if (err) {
            res.json({
              code: 500,
              data: err
            })
          } else {
            new CoustomerModel({ username, records }).save()
              .then(resp => {
                res.json({
                  code: 200,
                  data: resp
                })
              }).catch(err => {
                res.json({
                  code: 500,
                  data: err
                })
              })
          }
        })
      }

    }
  })
})

router.post('/getrecords', (req, res, next) => {
  const { username } = req.body
  CoustomerModel.find({ username }, (err, data) => {
    if (err) {
      res.json({
        code: 500,
        data: err
      })
    } else {
      res.json({
        code: 200,
        data: data
      })
    }
  })
})

module.exports = router